package cn.mujiankeji.mbrowser.功能.播放框.服务

import android.app.PendingIntent
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.hls.HlsMediaSource
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import cn.mujiankeji.mbrowser.app.MainActivity
import cn.mujiankeji.mbrowser.功能.播放框.核心.ExoHelper

/**
 * 播放服务类，用于后台播放媒体内容
 * 支持带有自定义请求头（如授权令牌）的HLS流播放
 */
@UnstableApi
class PlaybackService : MediaSessionService() {

    private var mediaSession: MediaSession? = null
    private lateinit var player: ExoPlayer
    private val exoHelper by lazy { ExoHelper(this) }

    override fun onCreate() {
        super.onCreate()
        initializePlayer()
    }

    private fun initializePlayer() {
        player = ExoPlayer.Builder(this).build()
        
        val sessionActivityPendingIntent =
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
            
        mediaSession = MediaSession.Builder(this, player)
            .setSessionActivity(sessionActivityPendingIntent)
            .build()
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? {
        return mediaSession
    }

    override fun onDestroy() {
        mediaSession?.run {
            player.release()
            release()
            mediaSession = null
        }
        super.onDestroy()
    }

    /**
     * 播放带有授权令牌的HLS流
     * @param url HLS流URL
     * @param token 授权令牌
     * @param startPositionMs 开始播放位置（毫秒）
     */
    fun playHlsWithToken(url: String, token: String, startPositionMs: Long = 0) {
        // 创建带有自定义请求头的DataSource.Factory
        val dataSourceFactory = DataSource.Factory {
            val dataSource = DefaultHttpDataSource.Factory().createDataSource()
            dataSource.setRequestProperty("Authorization", token)
            dataSource
        }
        
        // 创建HLS媒体源
        val mediaSource = HlsMediaSource.Factory(dataSourceFactory)
            .setAllowChunklessPreparation(true)
            .createMediaSource(MediaItem.fromUri(Uri.parse(url)))
        
        // 设置媒体源并播放
        player.setMediaSource(mediaSource)
        player.prepare()
        if (startPositionMs > 0) {
            player.seekTo(startPositionMs)
        }
        player.playWhenReady = true
    }
    
    /**
     * 播放普通媒体项
     * @param mediaItem 媒体项
     */
    fun playMediaItem(mediaItem: MediaItem) {
        player.setMediaItem(mediaItem)
        player.prepare()
        player.playWhenReady = true
    }
    
    companion object {
        /**
         * 创建带有授权令牌的媒体项
         * @param url 媒体URL
         * @param token 授权令牌
         * @return 配置好的MediaItem
         */
        fun createMediaItemWithToken(url: String, token: String): MediaItem {
            val extras = Bundle().apply {
                putString("Authorization", token)
            }
            
            return MediaItem.Builder()
                .setUri(url)
                .setMediaMetadata(androidx.media3.common.MediaMetadata.Builder()
                    .setExtras(extras)
                    .build())
                .build()
        }
    }
} 